<?php

namespace app\jigou\controller\qingdongams\event;

use addons\qingdongams\model\AftermarketType;
use addons\qingdongams\model\Consume;
use addons\qingdongams\model\EventNeeds;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\StaffSignIn;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\CustomerProduct;
use addons\qingdongams\model\Event as EventModel;
use fast\Tree;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 任务管理
 */
class Event extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new EventModel();
    }

    /**
     * 日程列表
     */
    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $createtime = input('createtime','');
            $wheres = [];
            if($createtime && $createtime !='null '){
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
                $wheres['createtime'] = array('between',array(strtotime($start),strtotime($end)));
            }
            $whereStaff = function ($query) {
                $query->where('create_staff_id|staff_id', 'in', Staff::getMyStaffIds())
                    ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_ids)");
            };
            $list = $this->model->with([
                'staff',
                'customer'
            ])->where($where)->where($wheres)->where($whereStaff)->order($sort, $order)->paginate($limit);
            $row = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加日程
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');

            if(isset($params["event_type"])){
                $params["event_type"] = implode("_", $params["event_type"]);
            }

            // 表单验证
            if (($result = $this->qingdongamsValidate($params,'Event', 'create')) !== true) {
                $this->error($result);
            }
            try {
                $result = EventModel::createEvent($params);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('添加成功');
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑日程
     */
    public function edit($ids=null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');

            if(isset($params["event_type"])){
                $params["event_type"] = implode("_", $params["event_type"]);
            }

            // 表单验证
            if (($result = $this->qingdongamsValidate($params,'Event', 'create')) !== true) {
                $this->error($result);
            }
            try {
                $result = EventModel::editEvent($params);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('添加成功');
            }
        }
        $event = EventModel::where(['id' => $ids])->with(['staff', 'customer','contacts'])->find();
        if (empty($event)) {
            $this->error('日程不存在');
        }
        $event['event_type']=explode('_',$event['event_type']);
        $this->view->assign('row',$event);
        Message::setRead(Message::EVENT_TYPE,$ids,$this->_staff->id);
        return $this->view->fetch();
    }

    /**
     * 日程详情
     */
    public function detail($ids=null)
    {

        $row=$this->model->with([
            'staff',
            'customer'
        ])->where(['id'=>$ids])->find();
        if (empty($row)) {
            $this->error('日程不存在');
        }
        
        $row['status_text'] = EventModel::getStatus($row['status']);
        $row['level_text'] = EventModel::getLevel($row['level']);
        $records=StaffSignIn::where([
            'relation_type'=>StaffSignIn::EVENT_TYPE,
            'relation_id'=>$row['id'],
        ])->with(['staff', 'customer'])->order('id desc')->select();
        Message::setRead(Message::EVENT_TYPE,$ids,$this->_staff->id);
        $this->assign('row',$row);
        $this->assign('records',$records);
        return $this->view->fetch();
    }


    /**
     * 获取费用
     */
    public function get_consume($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list   = Consume::where([
            'relation_type' => Consume::EVENT_TYPE,
            'relation_id' => $ids,
        ])->with(['staff'])->order('id desc')->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 添加客户需求
     */
    public function add_needs()
    {
        if ($this->request->isAjax()) {
            $row = input('row/a');
            $event_id = $row['event_id'] ?? '';
            $needs = $row['needs'] ?? '';
            if (empty($event_id) || empty($needs)) {
                $this->error('参数不能为空');
            }
            $data = [
                'event_id' => $event_id,
                'staff_id' => $this->_staff->id,
                'needs' => $needs
            ];
            $needs = new EventNeeds();
            $needs->save($data);

            $this->success('新增成功');
        }
        $event_id = input('event_id');
        $this->view->assign('event_id',$event_id);
        return $this->view->fetch();

    }

    /**
     * 客户需求列表
     */
    public function get_needs_list()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $event_id = input('event_id');
        $where = ['event_id' => $event_id];

        $needs = new EventNeeds();
        $list = $needs->where($where)->order('id desc')->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);

    }

    /**
     * 日程模板
     */
    public function get_event_template(){
        $this->view->engine->layout(false);
        $event_type=input('event_type');
        $template = 'qingdongams/event/event/template/';
        if ($event_type == '售后服务_上门_上门安装') {
            return $this->view->fetch($template . 'add3');
        }else if ($event_type == '售后服务_上门_上门维修') {
            $all = AftermarketType::where([])->select();
            $all = collection($all)->toArray();
            $tree = Tree::instance()->init($all, 'pid');
            $aftermarket_type = $tree->getTree(0, "<option value=@id @selected @disabled>@spacer@name</option>", '', '15,17');
            $this->view->assign('aftermarket_type',$aftermarket_type);
            return $this->view->fetch($template . 'add4');
        }else if ($event_type == '售后服务_返厂维修') {
            return $this->view->fetch($template . 'add5');
        }
        return '';
    }

    /**
     * 获取客户产品
     */
    public function getCustomerProduct()
    {
        $customer_id = input('customer_id', 0);
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $where['customer_id'] = $customer_id;
        $customerProduct = CustomerProduct::where($where)->with(['product'])->field('id,pay_date,product_id')->select();
        $list=[];
        foreach ($customerProduct as $v){
            $list[]=[
                'id'=>$v['id'],
                'name'=>$v['product']['name']."（{$v['pay_date']}）"
            ];
        }
        return json(['list' => $list, 'total' => count($list)]);
    }

    /**
     * 终止任务
     */
    public function revoke()
    {
        if ($this->request->isAjax()) {
            //日程状态 0未开始 1开始任务 2 已结束 3 已取消
            $ids = input('ids');
            $file_ids = input('file_ids', '');
            $content = input('content');


            $where = ['id' => $ids];
            $event = EventModel::where($where)->find();
            if (empty($event)) {
                $this->error('日程不存在');
            }
            if ($file_ids) {
                $file_ids = File::getId($file_ids);
            }
            $data = [
                'staff_id' => $this->auth->id,
                'file_ids' => $file_ids,
                'customer_id' => $event['relation_id'],//客户id
                'relation_process' => '任务终止',//日程类型
                'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
                'relation_id' => $event['id'],//签到关联id
                'content' => $content,
            ];
            Db::startTrans();
            try {
                //创建签到记录
                StaffSignIn::createSignIn($data);
                //修改日程状态
                EventModel::changeStatus($event['id'], 3);
                Message::addMessage(StaffSignIn::EVENT_TYPE, $event['id'], $event['create_staff_id'], $this->auth->id, "任务《{$event['title']}》被终止，请及时审阅!");
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                Log::error('错误:' . $e->getMessage());
                $this->error($e->getMessage());
            }

            $this->success('操作成功');
        }
        return $this->view->fetch();
    }
}